var app = getApp()
var WxParse = require('../../wxParse/wxParse.js');
Page({
  data: {
    storeName: '',
    storelogo: '',
    storelogoTemp: '',
    storeTel: '',
    storeContact: '',
    storeWechat: '',
    storeFl: [],
    storeFlIndex: '',
    opentime: '',
    endtime: '',
    curChooseAddr: '',
    curChooseLat: '',
    curChooseLng: '',
    storeAddress: '',
    storeDesc: '',
    shopImages: [],
    shopImagesTemp: [],
    settledTime: [],
    settledIndex: ''
  },
  onLoad: function (e) {
    var that = this;
    app.setNavtitle("修改信息");
    that.requestDetail();
  },
  requestDetail: function () {
    var that = this;
    var data = {
      map: 'applet_mobile_shop_detail'
    };
    data.lng = that.data.curChooseLongitude ? that.data.curChooseLongitude : 0;
    data.lat = that.data.curChooseLatitude ? that.data.curChooseLatitude : 0;
    console.log(data);
    wx.showLoading({
      title: '加载中',
      mask: true,
      time: 100000
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var detailInfo = res.data.data;
          that.setData({
            sid: detailInfo.id,
            storeName: detailInfo.name,
            storelogo: detailInfo.logo,
            storelogoTemp: detailInfo.logoTemp,
            storeTel: detailInfo.mobile,
            storeContact: detailInfo.contacts,
            opentime: detailInfo.openTime,
            endtime: detailInfo.closeTime,
            curChooseAddr: detailInfo.address,
            curChooseLat: detailInfo.lat,
            curChooseLng: detailInfo.lng,
            storeAddress: detailInfo.addrDetail,
            storeDesc: detailInfo.content,
            shopImages: detailInfo.imgs,
            shopImagesTemp: detailInfo.imgsTemp,
            mainBusiness: detailInfo.management,
            videoType: detailInfo.videoType,
            videoUrl: detailInfo.videoUrl ? detailInfo.videoUrl:''
          })
          that.requestCategory(res.data.data.categoryId);
        } else {
          console.log(res.data)
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  requestCategory: function (cateId) {
    var that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true,
      time: 100000
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_mobile_shop_apply_category'
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var storeFl = res.data.data;
          var storeFlIndex = '';
          for (var i = 0; i < storeFl.length;i++){
            if (storeFl[i].id == cateId){
              storeFlIndex = i;
            }
          }
          that.setData({
            storeFl: storeFl,
            storeFlIndex: storeFlIndex
          })
          console.log(that.data.storeFl);
          console.log(that.data.storeFlIndex);
        } else {
          console.log(res.data)
          // app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  submitApply: function () {
    var that = this;
    var storeFlArr = that.data.storeFl;
    var storeFlIndex = that.data.storeFlIndex;
    var data = {
      map: 'applet_mobile_shop_apply',
      name: that.data.storeName,
      logo: that.data.storelogoTemp,
      contacts: that.data.storeContact,
      mobile: that.data.storeTel,
      openTime: that.data.opentime,
      closeTime: that.data.endtime,
      lng: that.data.curChooseLng,
      lat: that.data.curChooseLat,
      address: that.data.curChooseAddr,
      management: that.data.mainBusiness,
      detail: that.data.storeAddress,
      content: that.data.storeDesc,
      cover: that.data.shopImagesTemp,
      cate: storeFlArr[storeFlIndex].id,
      sid: that.data.sid,
      videoType: that.data.videoType,
      videoUrl: that.data.videoUrl ? that.data.videoUrl : ''
    }
    console.log(data);
    if (!data.name) {
      app.errorTip(that, "请输入商家名称", 2000);
      return;
    }
    if (!data.logo) {
      app.errorTip(that, "请上传LOGO", 2000);
      return;
    }
    // if (!data.contacts) {
    //   app.errorTip(that, "请输入联系人", 2000);
    //   return;
    // }
    var isMob = /^(0|86|17951)?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/;
    var isPhone = /^(0[0-9]{2,3})([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
    if (!data.mobile) {
      app.errorTip(that, "请输入固定电话或手机号", 2000);
      return;
    }
    console.log(data.cate);
    if (!data.cate) {
      app.errorTip(that, "请选择所属分类", 2000);
      return;
    }
    // if (!data.openTime || !data.closeTime) {
    //   app.errorTip(that, "请选择营业时间", 2000);
    //   return;
    // }
    if (!data.lng || !data.lat || !data.address) {
      app.errorTip(that, "请选择所在位置", 2000);
      return;
    }
    // if (!data.detail) {
    //   app.errorTip(that, "请补充详细地址", 2000);
    //   return;
    // }
    // if (!data.content) {
    //   app.errorTip(that, "请输入商家信息", 2000);
    //   return;
    // }
    // if (data.cover.length <= 0) {
    //   app.errorTip(that, "请上传门店图片", 2000);
    //   return;
    // }
    that.requestSettled(data);
  },
  requestSettled: function (data, number) {
    var that = this;
    if (number) {
      data.number = number;
    }
    console.log(data);
    wx.showLoading({
      title: '加载中',
      mask: true,
      time: 100000
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          app.globalData.shopMsg = res.data.data.msg;
          app.globalData.isSettled = 1;
          wx.showModal({
            title: '提示',
            content: res.data.data.msg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
        } else {
          console.log(res.data)
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  requestPay: function (dataobj) {
    var that = this;
    var data = {
      map: 'applet_mobile_shop_pay',
      dateId: dataobj.payId,
      payType: that.data.payWay
    }
    console.log(data);
    wx.showLoading({
      title: '加载中',
      time: 100000,
      mask: true
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      dataType: 'json',
      success: function (res) {
        console.log(res);
        if (res.data.ec == 200) {
          var orderdata = res.data.data;
          console.log("支付方式" + data.payType)
          if (data.payType == 1) {
            console.log("微信支付");
            that.postPay(dataobj, orderdata.params, orderdata.number);
          } else {
            console.log("余额支付");
            that.requestSettled(dataobj, orderdata.number);
          }
        } else {
          console.log(res.data)
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  postPay: function (dataobj, params, tid) {
    var that = this;
    wx.requestPayment({
      'appId': params.appId,
      'timeStamp': params.timeStamp,
      'nonceStr': params.nonceStr,
      'package': params.package,
      'signType': params.signType,
      'paySign': params.paySign,
      'success': function (res) {
        wx.showLoading({
          title: '加载中',
        })
        setTimeout(function () {
          wx.hideLoading();
          that.requestSettled(dataobj, tid)
        }, 1000)
      },
      'fail': function (res) {
        console.log(res);
        wx.showModal({
          title: '',
          content: '支付失败',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {

            }
          }
        })
      }
    });
  },
  //表单值改变
  inputChange: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var value = e.detail.value;
    that.setData({
      [type]: value
    })
    // console.log(that.data);
  },
  chooseLocation: function () {
    var that = this;
    wx.chooseLocation({
      success: (res) => {
        console.log(res);
        that.setData({
          curChooseAddr: res.address,
          curChooseLat: res.latitude,
          curChooseLng: res.longitude
        })
      },
      fail: (res) => {
        wx.getSetting({
          success: (res) => {
            console.log(res.authSetting['scope.userLocation']);
            console.log(3333333333333);
            if (!res.authSetting['scope.userLocation']) {
              wx.openSetting({
                success: (res) => {
                  res.authSetting = {
                    "scope.userLocation": true
                  }
                }
              })
            }
          }
        })
      }
    })
  },
  // 单图上传
  chooseSingleImage: function (e) {
    var that = this;
    var imgtype = e.currentTarget.dataset.imgtype;
    console.log(imgtype);
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#333",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage('album', imgtype)
          } else if (res.tapIndex == 1) {
            that.chooseWxImage('camera', imgtype)
          }
        }
      }
    })
  },
  peiviewImg: function (e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = e.currentTarget.dataset.imgs;
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  //选择单图
  chooseWxImage: function (type, imgtype) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: [type],
      success: function (res) {
        console.log(res);
        var temPath = res.tempFilePaths[0];
        that.upload_file(temPath, imgtype);
      }
    })
  },
  // 上传单图到服务器
  upload_file: function (temPath, imgtype) {
    var that = this;
    var memberInfo = that.data.memberInfo;
    wx.showToast({
      title: '上传中',
      icon: 'loading',
      duration: 10000,
      mask: true
    });
    wx.uploadFile({
      url: app.globalData.requestUrl + '?&map=applet_img_upload',
      filePath: temPath,
      name: 'image',
      success: function (res) {
        var data = JSON.parse(res.data);
        var realpath = app.globalData.domin + data.data.path;
        if (data.ec == 200) {
          console.log(realpath);
          var savePath = imgtype + 'Temp';
          that.setData({
            [imgtype]: realpath,
            [savePath]: data.data.path
          })
          console.log(that.data[imgtype]);
          console.log(that.data[savePath]);
        } else {
          wx.showModal({
            title: '提示',
            content: data.em,
            showCancel: false
          });
        }
      },
      complete: function () {
        wx.hideToast();
      }
    });
  },
  //选择多图上传
  chooseMultiImage: function () {
    var that = this;
    var shopImages = that.data.shopImages;
    var shopImagesLength = 0;
    if (shopImages.length < 9) {
      shopImagesLength = 9 - shopImages.length;
    } else {
      shopImagesLength = 0;
    }
    console.log(shopImagesLength);
    app.chooseImageTap(this, shopImagesLength);
  },
  uploadImage: function () {//这里触发图片上传的方法
    var that = this;
    var temPaths = that.data.temPaths;
    var imgArr = that.data.shopImagesTemp;
    var shopImages = that.data.shopImages;
    that.uploadimg({
      url: app.globalData.requestUrl + '&map=applet_img_upload',//这里是你图片上传的接口
      path: temPaths//这里是选取的图片的地址数组
    }, imgArr, shopImages);
  },
  uploadimg: function (data, imgArr, shopImages) {
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.showToast({
      title: '上传中',
      icon: 'loading',
      duration: 10000,
      mask: true
    });
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'image',
      success: (resp) => {
        success++;
        var data = JSON.parse(resp.data);
        var curpath = data.data.path;
        var realpath = app.globalData.domin + data.data.path;
        console.log(shopImages);
        console.log(realpath);
        shopImages.push(realpath);
        imgArr.push(curpath);
      },
      fail: (res) => {
        fail++;
      },
      complete: () => {
        i++;
        if (i == data.path.length) {   //当图片传完时，停止调用        
          console.log('执行完毕');
          console.log('成功：' + success + " 失败：" + fail);
          console.log("dfs////////////");
          console.log(imgArr);
          console.log(shopImages);
          that.setData({
            shopImages: shopImages,
            shopImagesTemp: imgArr
          })
          console.log(that.data.shopImagesTemp);
          console.log("dfs////////////");
          wx.hideToast();
        } else {//若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data, imgArr, shopImages);
        }
      }
    });
  },
  delImg: function (e) {
    var that = this;
    var delIndex = e.target.dataset.index;
    var shopImages = that.data.shopImages;
    var imgArr = that.data.shopImagesTemp;
    console.log(shopImages);
    console.log(imgArr);
    wx.showModal({
      title: '删除提示',
      content: '确定要删除该图片吗？',
      success: function (res) {
        if (res.confirm) {
          shopImages.splice(delIndex, 1);
          imgArr.splice(delIndex, 1);
          that.setData({
            shopImages: shopImages,
            shopImagesTemp: imgArr
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  myShopinfo: function () {
    var shopStatus = app.globalData.shopStatus;
    wx.redirectTo({
      url: '/subpages/shopTelinfo/shopTelinfo?status=' + shopStatus
    })
  },
  payRadioChange: function (e) {
    this.setData({
      payWay: e.detail.value
    })
    console.log(this.data.payWay);
  },
  // 切换选择协议
  toggleAgree: function () {
    var that = this;
    var isAgree = that.data.isAgreement;
    if (isAgree == 1) {
      that.setData({
        isAgreement: 0
      })
    } else {
      that.setData({
        isAgreement: 1
      })
    }
  },
  showAgreement: function () {
    this.setData({
      isShowAgreement: true
    })
  },
  hideAgreement: function () {
    this.setData({
      isShowAgreement: false
    })
  },
  videoTypeChange: function (e) {
    var that = this;
    that.setData({
      videoType: e.detail.value
    })
    console.log(that.data.videoType)
  }
})